var fs = require('fs')
var rp = require('request-promise')
var cheerio = require('cheerio')

var config = require('./config.js')
var util = require('./util/_default.js')
var xlsx = require('node-xlsx')
var xdl = require('./xdl.js')

var proxyUrl = '',trycount=10
var page,maxpage

var args = process.argv.splice(2)

var helper = util.helper
var dbHelper = util.dbHelper
var logHelper = util.logHelper
var yzmHelper = util.yzmHelper

var dt = [['序号', '流水号', '目录编号', '实际通用名', '实际剂型', '实际规格',
    '包装', '剂型说明', '包材', '包材说明', '附加装置', '中药成分', '生产企业', '投标企业', '限价', '限价制定单位']]

var href = 'http://ypzb2015gs.lnypcg.com.cn/BidInfoPublic/Genuine/GS_BidGoodsList3.aspx'

function main() {
    page = args[0]
    maxpage = args[1]

    var opts = helper.deepCopy(config.reqOpts)
    opts.url = href
    opts.method = 'GET'
    opts.proxy = proxyUrl
    opts.headers.Referer = href

    rp(opts).then(function (body) {

        var $ = cheerio.load(body)
        var data = helper.getFormData($('form#form1').serializeArray())
        data['btnQuery'] = '查询'
        GetDetail(data, page)

    }).catch(function (err) {
        console.log(err)
        setTimeout(function () {
            main()
        }, Math.random() * 10 * 1000)
    })
}
function GetDetail(data, page) {
    console.log('当前页：'+page+',当前总数：'+dt.length)
    var opts = helper.deepCopy(config.reqOpts)
    data['txtGoodsID'] = page
    opts.url = href
    opts.method = 'POST'
    opts.headers.Referer = href
    opts.formData = data
    opts.proxy = proxyUrl
    rp(opts).then(function (body) {
        if (body.indexOf('暂无符合条件的数据') > 0) {
            page++
            //console.log(body)
            GetDetail(data, page)
        } else {
            var $ = cheerio.load(body)
            var d = helper.getFormData($('form#form1').serializeArray())
            var tr = $('tr', 'table.mainlist')
            if (tr.length > 1) {
                var row = []
                $('td', tr.eq(1)).each(function (v, i, a) {
                    row.push($(this).text().trim())
                })
                dt.push(row)
                if (dt.length % 99 == 0) {
                    saveExcel(dt, 0)
                }
                page++
                if (page <= maxpage) {
                    GetDetail(data, page)
                } else {
                    saveExcel(dt, 1)
                }
            }
            else{
                if(body.indexOf('您对该页面的访问过于频繁')>0){
                    proxyUrl = xdl.proxy()
                }
                GetDetail(data, page)
            }

        }
    }).catch(function (err) {
        console.log(err)
        setTimeout(function () {
            GetDetail(data, page)
        }, Math.random() * 10 * 1000)
    })

}

function saveExcel(data, t) {
    var d = 'finished'
    if (t == 0) {
        d = (new Date()).Format('hhmmss')
    }
    var file = xlsx.build([{ name: "mySheetName", data: data }])
    fs.writeFileSync('result_' + page + '_' + d + '.xlsx', file, 'binary')
}

function check(body) {
    var result = false
    if (body.indexOf('charset=gbk2312') > 0 || body.indexOf('My97DatePicker') < 0) {
        result = true
    }
    return result
}

main()



